package com.api.controller;

import com.api.mapper.BuildingMapper;
import com.api.mapper.ChamberMapper;
import com.api.mapper.UpkeepMapper;
import com.api.mapper.UserMapper;
import com.api.pojo.Upkeep;
import com.api.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/upkeep")
public class UpkeepController {

    @Autowired
    UpkeepMapper um;

    @Autowired
    UserMapper usm;

    @Autowired
    BuildingMapper bm;

    @Autowired
    ChamberMapper cm;

    @RequestMapping("/create")
    public Map<String, Object> create(Upkeep upkeep) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        um.create(upkeep);
        map.put("data", true);
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    @RequestMapping("/remove")
    public Map<String, Object> remove(Integer id) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        um.remove(id);
        map.put("data", true);
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    @RequestMapping("/update")
    public Map<String, Object> update(Upkeep upkeep) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        um.update(upkeep);
        map.put("data", true);
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }

    @RequestMapping("/get")
    public Map<String, Object> get(Integer pageNo, Integer pageSize, Integer uid) {
        Map<String,Object> map = new HashMap<>();
        int code = 200;
        String msg = "ok";

        pageNo = --pageNo * pageSize;
        List<Upkeep> list = uid == null ? um.get(pageNo, pageSize) : um.getByUid(pageNo, pageSize, uid);
        list.forEach(e -> {
            User user = usm.getById(e.getUid());
            user.setBuilding(bm.getById(user.getBid()));
            user.setChamber(cm.getById(user.getCid()));
            e.setUser(user);
            e.setExecutorUser(usm.getById(e.getExecutor()));
        });
        map.put("data", list);
        map.put("total", uid == null ? um.count() : um.countByUid(uid));
        map.put("code", code);
        map.put("msg", msg);
        return map;
    }
}
